import { optionsName, optionsCache } from '@/settings'

export const getLocalDict = (key) => {
  const now = new Date().getTime()
  const refreshTip = localStorage.getItem(`${optionsName}_last`)
  const refreshKey = `${key}`
  const refreshData = localStorage.getItem(optionsName)

  if (refreshTip && now - refreshTip < optionsCache) {
    try {
      const local_dict_data = JSON.parse(refreshData)
      const options = local_dict_data[refreshKey]
      if (local_dict_data && options) {
        return { ...options }
      }
    } catch (error) {
      return null
    }
  } else {
    return null
  }
}

export const setLocalDict = (key, data) => {
  const now = new Date().getTime()
  const refreshKey = `${key}`
  const refreshData = localStorage.getItem(optionsName)

  try {
    let origindata = refreshData ? JSON.parse(refreshData) : {}
    origindata[refreshKey] = data
    localStorage.setItem(optionsName, JSON.stringify(origindata))
    localStorage.setItem(`${optionsName}_last`, now)
  } catch (error) {
    const d = {}
    d[refreshKey] = data
    localStorage.setItem(optionsName, JSON.stringify(d))
    localStorage.setItem(`${optionsName}_last`, now)
  }
  // debugger
}
